#include "log_handler.h"

LogHandler::LogHandler() {
	pthread_mutex_init(&mutex, NULL);
}

LogHandler::~LogHandler() {
	pthread_mutex_destroy(&mutex);
}

void LogHandler::log(int level, int mask, const char *text, const char *file) {
	if (level == LOG_DEBUG)
		debug(mask, text, file);
	else if (level == LOG_INFO)
		info(mask, text, file);
	else if (level == LOG_ERROR)
		error(mask, text, file);
}

void LogHandler::debug(int mask, const char *text, const char *file) {
	if (mask & LOG_STDOUT) {
		pthread_mutex_lock(&mutex);
		write(1, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}
	if (mask & (LOG_FILE)) {
		pthread_mutex_lock(&mutex);
		int fd = open(file, O_APPEND);
		write(fd, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}
}

void LogHandler::info(int mask, const char *text, const char *file) {
	if (mask & LOG_STDOUT) {
		pthread_mutex_lock(&mutex);
		write(1, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}
	if (mask & LOG_FILE) {
		pthread_mutex_lock(&mutex);
		int fd = open(file, O_APPEND);
		write(fd, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}
}

void LogHandler::error(int mask, const char *text, const char *file) {
	if (mask & LOG_STDOUT) {
		pthread_mutex_lock(&mutex);
		write(1, "error: ", 7);
		write(1, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}
	if (mask & LOG_FILE) {
		pthread_mutex_lock(&mutex);
		int fd = open(file, O_APPEND);
		write(fd, "error: ", 7);
		write(fd, text, strlen(text));
		pthread_mutex_unlock(&mutex);
	}

}
